<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\Menu;
use app\admin\validate\AdminForm;
use app\admin\validate\AuthForm;
use app\admin\validate\RoleForm;
use think\Db;
use think\Request;
use think\Validate;

class Auth extends Common
{

    public function menu(){
        return view('',['data'=>Menu::getMenuList()]);
    }

    public function add(){
        if(Request()->isPost()){
            $AuthForm = new AuthForm();
            $data = input('post.');
            if (!$AuthForm->check($data)) {
                return package(20001,$AuthForm->getError());
            }
            $result = $AuthForm->addForm($data);
            return package($result['code'],$result['msg']);
        }else{
            $menuList =Menu::getMenuList();
            return view('edit_view',['type'=>'add','menuList'=>$menuList]);
        }
    }
    public function edit_view(){
        if(Request()->isPost()) {
            $AuthForm = new AuthForm();
            $data = input('post.');
            if (!$AuthForm->check($data)) {
                return package(20001,$AuthForm->getError());
            }
            $id = isset($data['id'])?intval($data['id']):0;
            if(!$id){
                return package(20001,'id错误！');
            }
            return checkRes((new Menu())->edit($id,$data),'修改');
        }else{
            $id = input('param.id',0);
            $info = Menu::getMenuInfo($id);
            if(!$info){
                $this->error('id错误');
            }
            $menuList =Menu::getMenuList();
            return view('edit_view',
                [
                    'type'=>'edit_view',
                    'menuList'=>$menuList,
                    'infos'=>$info
                ]);
        }
    }
    public function role(){
        return view('',['type'=>'add','roleList'=>Admin::getRole()]);
    }
    //添加角色
    public function addrole(){
        if(Request()->isPost()){
            $AuthForm = new RoleForm();
            $data = input('post.');
            if(isset($data['is_active'])){
                $data['is_active'] = 1;
            }else $data['is_active'] =0;
            if (!$AuthForm->check($data)) {
                return package(20001,$AuthForm->getError());
            }
            $result = $AuthForm->add($data);
            return package($result['code'],$result['msg']);
        }else
            return view('role_edit',['type'=>'addrole']);
    }
    public function authrole(){
        if(Request()->isPost()) {
            $data = input('post.menu',[]);
            $role_id = input('post.role_id',0,'int');
            if(!$role_id){
                return package(20002,'请选择角色！');
            }
            if(!$data){
                return package(20002,'选择错误！');
            }
            $in ='';
            foreach ($data as $v){
                $in.=$v.',';
            }
            $list  =  Menu::getMenuIn('id',$in,'id,name,router_url,is_show,parent_id,icon');
            foreach($list as $key=>$v){
                $list[$key]->role_id = $role_id;
                $list[$key]->router_id = $v['id'];
                unset($list[$key]->id);
            }
            if(Admin::addRoleAccess($list->toArray(),$role_id)){
                return package(0,'权限分配成功！');
            }else{
                return package(20001,'权限分配失败！');
            }

        }else{
            $access= Db::name("role_access")
                ->where('role_id',input('param.role_id'))
                ->field('router_url')
                ->select();
            $list = Menu::getMenuList(1,'id,name,parent_id,router_url');
            return view('',[
                'menuList'=>$list,
                'type'=>'authrole',
                'access'=>serialize($access)
            ]);
        }
    }
    public function admin(){
        $result = Admin::getAdmin('id,nickname,role_name,username,headlike,is_supper,create_time,lock,login_time');
        return view('',['data'=>$result]);
    }
    public function adminedit()
    {
        if (Request()->isPost()) {
           $data =input('post.');
            $validate = new AdminForm();
            if (!$validate->check($data)) {
                return package(20001,$validate->getError());
            }
            if($data['password'] !=$data['to_password'])
                return package(20001, '两次密码输入不一致！');
            $result = $validate->editUser($data);
            return package($result['code'],$result['msg']);
        }else{
            $admin_id = input('param.admin_id', '', 0);
            if (!$admin_id) {
                return package(20001, '管理员id错误！');
            }
            $info = Admin::getAdminInfoByid($admin_id, 'id,nickname,role_name,username,headlike,is_supper,lock,role_id');
            return view('', ['info' => $info, 'role' => Admin::getRole('name,id'), 'type' => 'adminedit']);
        }
    }
    public function addUser(){
        if (Request()->isPost()) {
            $data =input('post.');
            $validate = new AdminForm();
            if (!$validate->check($data)) {
                return package(20001,$validate->getError());
            }
            if($data['password'] !=$data['to_password'])
                return package(20001, '两次密码输入不一致！');
            $result = $validate->addUser($data);
            return package($result['code'],$result['msg']);
        }else{
            return view('adminedit', ['role' => Admin::getRole('name,id'), 'type' => 'addUser']);
        }
    }
    public function edit_pwd(){
        if (Request()->isPost()) {
            $data = input('post.');
            $res = Validate::make()
                ->rule([
                    'old_password|原密码'=>"require",
                    'password|新密码' =>'require|min:6|max:128',
                ]);
            if (!$res->check($data)) {
                return package('10008', $res->getError());
            }
            if ($data['old_password'] ==$data['password']){
                return package('10009', "原密码和新密码不能相同！");
            }

            $adminInfo = session('admin'.ADMINTYPE);
            $dbName = "";
            if(ADMINTYPE ==1){
                $dbName = "admin";
            }else{
                $dbName = "join_user";
            }
            if(!checkPass($data['old_password'],Db::name($dbName)->where('username',$adminInfo['username'])->value('password'))){
                return package('10009', "原密码错误！");
            }
            if(Db::name($dbName)->where('username',$adminInfo['username'])->update(['password'=>pass($data['password'])])){
                return package(0, "修改成功！");
            }else{
                return package(20006,'修改失败');
            }


        }else{
            return view('',['type'=>"edit_pwd"]);
        }
    }
    public function edit_pay_pwd(){
        if (Request()->isPost()) {
            $data = input('post.');
            $res = Validate::make()
                ->rule([
                    'old_password|原密码'=>"require",
                    'password|新支付密码' =>'require|min:6|max:18|/(?=.*[a-z])(?=.*\d)(?=.*[#@!~%^&*.-_])[a-z\d#@!~%^&*.-_]{6,18}/i',
                ])
                ->message(['password./(?=.*[a-z])(?=.*\d)(?=.*[#@!~%^&*.-_])[a-z\d#@!~%^&*.-_]{6,18}/i'=>"密码必须是数字字母符号格式！"]);
            if (!$res->check($data)) {
                return package('10008', $res->getError());
            }
            if ($data['old_password'] ==$data['password']){
                return package('10009', "原密码和新密码不能相同！");
            }
            $adminInfo = session('admin');
            if(!checkPass($data['old_password'],Db::name('admin')->where('username',$adminInfo['username'])->value('pay_password'))){
                return package('10009', "原密码错误！");
            }
            if(Db::name('admin')->where('username',$adminInfo['username'])->update(['pay_password'=>pass($data['password'])])){
                return package(0, "修改成功！");
            }else{
                return package(20006,'修改失败');
            }


        }else{
            return view('',['type'=>"edit_pay_pwd"]);
        }
    }
}